package com.vipbbo.spring.aop;

import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class JDKProxyFactory implements InvocationHandler {
	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

	/**
	 * 	要返回的代理对象
	 */
	private Object obj;

	public Object createProxyIntance(Object obj){
		this.obj=obj;
		//第一个参数是目标对象的类加载器
		//第二个参数是目标对象实现的接口
		//第三个参数传入一个InvocationHandler实例，该参数和回调有关系。
		System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),this);

	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object proxyObject=null;
		DoServiceImpl ds=(DoServiceImpl)obj;
		if(ds.getUserName()!=null){
			proxyObject= method.invoke(ds, args);
		}else{
			System.out.println("用户名为空，已拦截");
		}
		return proxyObject;
	}
}
